const multer = require('multer')
const MAO = require('multer-aliyun-oss')
const OSS = require('ali-oss')
const { BadRequestError } = require('../utils/errors')

// 阿里云配置
const config = {
  region: process.env.ALIYUN_REGION,
  accessKeyId: process.env.ALIYUN_ACCESS_KEY_ID,
  accessKeySecret: process.env.ALIYUN_ACCESS_SECRET,
  bucket: process.env.ALIYUN_BUCKET
}

const client = new OSS(config)

// multer 配置
const upload = multer({
  storage: MAO({
    config: config,
    destination: 'uploads', // 自定义上传目录
  }),
  limits: {
    fileSize: 5 * 1024 * 1024, // 文件大小限制为5MB
  },
  fileFilter: function(req, files, cb) {
    const fileType = files.mimetype.split('/')[0]
    const isImage = fileType === 'image'
    if (!isImage) {
      return cb(new BadRequestError('只允许上传图片'))
    }
    db(null, true)
  }
})

// 单文件上传，指定表单字段名 file
const singleFileUpload = upload.single('file')

module.exports = {
  config,
  // client,
  singleFileUpload,
}